{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "77gENRVX40S7"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "d8jyt37T42Vf"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "aPxHdjwW5P2j"
      },
      "outputs": [],
      "source": [
        "#@title MIT License\n",
        "#\n",
        "# Copyright (c) 2017 François Chollet                                                                                                                    # IGNORE_COPYRIGHT: cleared by OSS licensing\n",
        "#\n",
        "# Permission is hereby granted, free of charge, to any person obtaining a\n",
        "# copy of this software and associated documentation files (the \"Software\"),\n",
        "# to deal in the Software without restriction, including without limitation\n",
        "# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n",
        "# and/or sell copies of the Software, and to permit persons to whom the\n",
        "# Software is furnished to do so, subject to the following conditions:\n",
        "#\n",
        "# The above copyright notice and this permission notice shall be included in\n",
        "# all copies or substantial portions of the Software.\n",
        "#\n",
        "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
        "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
        "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n",
        "# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
        "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n",
        "# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n",
        "# DEALINGS IN THE SOFTWARE."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hRTa3Ee15WsJ"
      },
      "source": [
        "# Transfer learning and fine-tuning"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dQHMcypT3vDT"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/images/transfer_learning\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/images/transfer_learning.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2X4KyhORdSeO"
      },
      "source": [
        "In this tutorial, you will learn how to classify images of cats and dogs by using transfer learning from a pre-trained network.\n",
        "\n",
        "A pre-trained model is a saved network that was previously trained on a large dataset, typically on a large-scale image-classification task. You either use the pretrained model as is or use transfer learning to customize this model to a given task.\n",
        "\n",
        "The intuition behind transfer learning for image classification is that if a model is trained on a large and general enough dataset, this model will effectively serve as a generic model of the visual world. You can then take advantage of these learned feature maps without having to start from scratch by training a large model on a large dataset.\n",
        "\n",
        "In this notebook, you will try two ways to customize a pretrained model:\n",
        "\n",
        "1. Feature Extraction: Use the representations learned by a previous network to extract meaningful features from new samples. You simply add a new classifier, which will be trained from scratch, on top of the pretrained model so that you can repurpose the feature maps learned previously for the dataset.\n",
        "\n",
        " You do not need to (re)train the entire model. The base convolutional network already contains features that are generically useful for classifying pictures. However, the final, classification part of the pretrained model is specific to the original classification task, and subsequently specific to the set of classes on which the model was trained.\n",
        "\n",
        "1. Fine-Tuning: Unfreeze a few of the top layers of a frozen model base and jointly train both the newly-added classifier layers and the last layers of the base model. This allows us to \"fine-tune\" the higher-order feature representations in the base model in order to make them more relevant for the specific task.\n",
        "\n",
        "You will follow the general machine learning workflow.\n",
        "\n",
        "1. Examine and understand the data\n",
        "1. Build an input pipeline, in this case using Keras ImageDataGenerator\n",
        "1. Compose the model\n",
        "   * Load in the pretrained base model (and pretrained weights)\n",
        "   * Stack the classification layers on top\n",
        "1. Train the model\n",
        "1. Evaluate model\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TqOt6Sv7AsMi"
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import os\n",
        "import tensorflow as tf\n",
        "\n",
        "from tensorflow.keras.preprocessing import image_dataset_from_directory"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "v77rlkCKW0IJ"
      },
      "source": [
        "## Data preprocessing"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0GoKGm1duzgk"
      },
      "source": [
        "### Data download"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vHP9qMJxt2oz"
      },
      "source": [
        "In this tutorial, you will use a dataset containing several thousand images of cats and dogs. Download and extract a zip file containing the images, then create a `tf.data.Dataset` for training and validation using the `tf.keras.preprocessing.image_dataset_from_directory` utility. You can learn more about loading images in this [tutorial](https://www.tensorflow.org/tutorials/load_data/images)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ro4oYaEmxe4r"
      },
      "outputs": [],
      "source": [
        "_URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'\n",
        "path_to_zip = tf.keras.utils.get_file('cats_and_dogs.zip', origin=_URL, extract=True)\n",
        "PATH = os.path.join(os.path.dirname(path_to_zip), 'cats_and_dogs_filtered')\n",
        "\n",
        "train_dir = os.path.join(PATH, 'train')\n",
        "validation_dir = os.path.join(PATH, 'validation')\n",
        "\n",
        "BATCH_SIZE = 32\n",
        "IMG_SIZE = (160, 160)\n",
        "\n",
        "train_dataset = image_dataset_from_directory(train_dir,\n",
        "                                             shuffle=True,\n",
        "                                             batch_size=BATCH_SIZE,\n",
        "                                             image_size=IMG_SIZE)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cAvtLwi7_J__"
      },
      "outputs": [],
      "source": [
        "validation_dataset = image_dataset_from_directory(validation_dir,\n",
        "                                                  shuffle=True,\n",
        "                                                  batch_size=BATCH_SIZE,\n",
        "                                                  image_size=IMG_SIZE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yO1Q2JaW5sIy"
      },
      "source": [
        "Show the first nine images and labels from the training set:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "K5BeQyKThC_Y"
      },
      "outputs": [],
      "source": [
        "class_names = train_dataset.class_names\n",
        "\n",
        "plt.figure(figsize=(10, 10))\n",
        "for images, labels in train_dataset.take(1):\n",
        "  for i in range(9):\n",
        "    ax = plt.subplot(3, 3, i + 1)\n",
        "    plt.imshow(images[i].numpy().astype(\"uint8\"))\n",
        "    plt.title(class_names[labels[i]])\n",
        "    plt.axis(\"off\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EZqCX_mpV3Mx"
      },
      "source": [
        "As the original dataset doesn't contain a test set, you will create one. To do so, determine how many batches of data are available in the validation set using ```tf.data.experimental.cardinality```, then move 20% of them to a test set."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "uFFIYrTFV9RO"
      },
      "outputs": [],
      "source": [
        "val_batches = tf.data.experimental.cardinality(validation_dataset)\n",
        "test_dataset = validation_dataset.take(val_batches // 5)\n",
        "validation_dataset = validation_dataset.skip(val_batches // 5)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Q9pFlFWgBKgH"
      },
      "outputs": [],
      "source": [
        "print('Number of validation batches: %d' % tf.data.experimental.cardinality(validation_dataset))\n",
        "print('Number of test batches: %d' % tf.data.experimental.cardinality(test_dataset))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MakSrdd--RKg"
      },
      "source": [
        "### Configure the dataset for performance"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "22XWC7yjkZu4"
      },
      "source": [
        "Use buffered prefetching to load images from disk without having I/O become blocking. To learn more about this method see the [data performance](https://www.tensorflow.org/guide/data_performance) guide."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p3UUPdm86LNC"
      },
      "outputs": [],
      "source": [
        "AUTOTUNE = tf.data.AUTOTUNE\n",
        "\n",
        "train_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE)\n",
        "validation_dataset = validation_dataset.prefetch(buffer_size=AUTOTUNE)\n",
        "test_dataset = test_dataset.prefetch(buffer_size=AUTOTUNE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MYfcVwYLiR98"
      },
      "source": [
        "### Use data augmentation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bDWc5Oad1daX"
      },
      "source": [
        "When you don't have a large image dataset, it's a good practice to artificially introduce sample diversity by applying random, yet realistic, transformations to the training images, such as rotation and horizontal flipping. This helps expose the model to different aspects of the training data and reduce [overfitting](https://www.tensorflow.org/tutorials/keras/overfit_and_underfit). You can learn more about data augmentation in this [tutorial](https://www.tensorflow.org/tutorials/images/data_augmentation)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3P99QiMGit1A"
      },
      "outputs": [],
      "source": [
        "data_augmentation = tf.keras.Sequential([\n",
        "  tf.keras.layers.experimental.preprocessing.RandomFlip('horizontal'),\n",
        "  tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),\n",
        "])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s9SlcbhrarOO"
      },
      "source": [
        "Note: These layers are active only during training, when you call `model.fit`. They are inactive when the model is used in inference mode in `model.evaulate` or `model.fit`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9mD3rE2Lm7-d"
      },
      "source": [
        "Let's repeatedly apply these layers to the same image and see the result."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aQullOUHkm67"
      },
      "outputs": [],
      "source": [
        "for image, _ in train_dataset.take(1):\n",
        "  plt.figure(figsize=(10, 10))\n",
        "  first_image = image[0]\n",
        "  for i in range(9):\n",
        "    ax = plt.subplot(3, 3, i + 1)\n",
        "    augmented_image = data_augmentation(tf.expand_dims(first_image, 0))\n",
        "    plt.imshow(augmented_image[0] / 255)\n",
        "    plt.axis('off')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bAywKtuVn8uK"
      },
      "source": [
        "### Rescale pixel values\n",
        "\n",
        "In a moment, you will download `tf.keras.applications.MobileNetV2` for use as your base model. This model expects pixel values in `[-1, 1]`, but at this point, the pixel values in your images are in `[0, 255]`. To rescale them, use the preprocessing method included with the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cO0HM9JAQUFq"
      },
      "outputs": [],
      "source": [
        "preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xnr81qRMzcs5"
      },
      "source": [
        "Note: Alternatively, you could rescale pixel values from `[0, 255]` to `[-1, 1]` using a [Rescaling](https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/Rescaling) layer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "R2NyJn4KQMux"
      },
      "outputs": [],
      "source": [
        "rescale = tf.keras.layers.experimental.preprocessing.Rescaling(1./127.5, offset= -1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Wz7qgImhTxw4"
      },
      "source": [
        "Note: If using other `tf.keras.applications`, be sure to check the API doc to determine if they expect pixels in `[-1, 1]` or `[0, 1]`, or use the included `preprocess_input` function."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OkH-kazQecHB"
      },
      "source": [
        "## Create the base model from the pre-trained convnets\n",
        "You will create the base model from the **MobileNet V2** model developed at Google. This is pre-trained on the ImageNet dataset, a large dataset consisting of 1.4M images and 1000 classes. ImageNet is a research training dataset with a wide variety of categories like `jackfruit` and `syringe`. This base of knowledge will help us classify cats and dogs from our specific dataset.\n",
        "\n",
        "First, you need to pick which layer of MobileNet V2 you will use for feature extraction. The very last classification layer (on \"top\", as most diagrams of machine learning models go from bottom to top) is not very useful.  Instead, you will follow the common practice to depend on the very last layer before the flatten operation. This layer is called the \"bottleneck layer\". The bottleneck layer features retain more generality as compared to the final/top layer.\n",
        "\n",
        "First, instantiate a MobileNet V2 model pre-loaded with weights trained on ImageNet. By specifying the **include_top=False** argument, you load a network that doesn't include the classification layers at the top, which is ideal for feature extraction."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "19IQ2gqneqmS"
      },
      "outputs": [],
      "source": [
        "# Create the base model from the pre-trained model MobileNet V2\n",
        "IMG_SHAPE = IMG_SIZE + (3,)\n",
        "base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n",
        "                                               include_top=False,\n",
        "                                               weights='imagenet')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AqcsxoJIEVXZ"
      },
      "source": [
        "This feature extractor converts each `160x160x3` image into a `5x5x1280` block of features. Let's see what it does to an example batch of images:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Y-2LJL0EEUcx"
      },
      "outputs": [],
      "source": [
        "image_batch, label_batch = next(iter(train_dataset))\n",
        "feature_batch = base_model(image_batch)\n",
        "print(feature_batch.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rlx56nQtfe8Y"
      },
      "source": [
        "## Feature extraction\n",
        "In this step, you will freeze the convolutional base created from the previous step and to use as a feature extractor. Additionally, you add a classifier on top of it and train the top-level classifier."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CnMLieHBCwil"
      },
      "source": [
        "### Freeze the convolutional base"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7fL6upiN3ekS"
      },
      "source": [
        "It is important to freeze the convolutional base before you compile and train the model. Freezing (by setting layer.trainable = False) prevents the weights in a given layer from being updated during training. MobileNet V2 has many layers, so setting the entire model's `trainable` flag to False will freeze all of them."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OTCJH4bphOeo"
      },
      "outputs": [],
      "source": [
        "base_model.trainable = False"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jsNHwpm7BeVM"
      },
      "source": [
        "### Important note about BatchNormalization layers\n",
        "\n",
        "Many models contain `tf.keras.layers.BatchNormalization` layers. This layer is a special case and precautions should be taken in the context of fine-tuning, as shown later in this tutorial. \n",
        "\n",
        "When you set `layer.trainable = False`, the `BatchNormalization` layer will run in inference mode, and will not update its mean and variance statistics. \n",
        "\n",
        "When you unfreeze a model that contains BatchNormalization layers in order to do fine-tuning, you should keep the BatchNormalization layers in inference mode by passing `training = False` when calling the base model. Otherwise, the updates applied to the non-trainable weights will destroy what the model has learned.\n",
        "\n",
        "For details, see the [Transfer learning guide](https://www.tensorflow.org/guide/keras/transfer_learning)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KpbzSmPkDa-N"
      },
      "outputs": [],
      "source": [
        "# Let's take a look at the base model architecture\n",
        "base_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wdMRM8YModbk"
      },
      "source": [
        "### Add a classification head"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QBc31c4tMOdH"
      },
      "source": [
        "To generate predictions from the block of features, average over the spatial `5x5` spatial locations, using a `tf.keras.layers.GlobalAveragePooling2D` layer to convert the features to  a single 1280-element vector per image."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dLnpMF5KOALm"
      },
      "outputs": [],
      "source": [
        "global_average_layer = tf.keras.layers.GlobalAveragePooling2D()\n",
        "feature_batch_average = global_average_layer(feature_batch)\n",
        "print(feature_batch_average.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O1p0OJBR6dOT"
      },
      "source": [
        "Apply a `tf.keras.layers.Dense` layer to convert these features into a single prediction per image. You don't need an activation function here because this prediction will be treated as a `logit`, or a raw prediction value.  Positive numbers predict class 1, negative numbers predict class 0."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Wv4afXKj6cVa"
      },
      "outputs": [],
      "source": [
        "prediction_layer = tf.keras.layers.Dense(1)\n",
        "prediction_batch = prediction_layer(feature_batch_average)\n",
        "print(prediction_batch.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HXvz-ZkTa9b3"
      },
      "source": [
        "Build a model by chaining together the data augmentation, rescaling, base_model and feature extractor layers using the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional). As previously mentioned, use training=False as our model contains a BatchNormalization layer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DgzQX6Veb2WT"
      },
      "outputs": [],
      "source": [
        "inputs = tf.keras.Input(shape=(160, 160, 3))\n",
        "x = data_augmentation(inputs)\n",
        "x = preprocess_input(x)\n",
        "x = base_model(x, training=False)\n",
        "x = global_average_layer(x)\n",
        "x = tf.keras.layers.Dropout(0.2)(x)\n",
        "outputs = prediction_layer(x)\n",
        "model = tf.keras.Model(inputs, outputs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "g0ylJXE_kRLi"
      },
      "source": [
        "### Compile the model\n",
        "\n",
        "Compile the model before training it. Since there are two classes, use a binary cross-entropy loss with `from_logits=True` since the model provides a linear output."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RpR8HdyMhukJ"
      },
      "outputs": [],
      "source": [
        "base_learning_rate = 0.0001\n",
        "model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),\n",
        "              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I8ARiyMFsgbH"
      },
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lxOcmVr0ydFZ"
      },
      "source": [
        "The 2.5M parameters in MobileNet are frozen, but there are 1.2K _trainable_ parameters in the Dense layer.  These are divided between two `tf.Variable` objects, the weights and biases."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "krvBumovycVA"
      },
      "outputs": [],
      "source": [
        "len(model.trainable_variables)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RxvgOYTDSWTx"
      },
      "source": [
        "### Train the model\n",
        "\n",
        "After training for 10 epochs, you should see ~94% accuracy on the validation set.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Om4O3EESkab1"
      },
      "outputs": [],
      "source": [
        "initial_epochs = 10\n",
        "\n",
        "loss0, accuracy0 = model.evaluate(validation_dataset)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8cYT1c48CuSd"
      },
      "outputs": [],
      "source": [
        "print(\"initial loss: {:.2f}\".format(loss0))\n",
        "print(\"initial accuracy: {:.2f}\".format(accuracy0))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JsaRFlZ9B6WK"
      },
      "outputs": [],
      "source": [
        "history = model.fit(train_dataset,\n",
        "                    epochs=initial_epochs,\n",
        "                    validation_data=validation_dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Hd94CKImf8vi"
      },
      "source": [
        "### Learning curves\n",
        "\n",
        "Let's take a look at the learning curves of the training and validation accuracy/loss when using the MobileNet V2 base model as a fixed feature extractor."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "53OTCh3jnbwV"
      },
      "outputs": [],
      "source": [
        "acc = history.history['accuracy']\n",
        "val_acc = history.history['val_accuracy']\n",
        "\n",
        "loss = history.history['loss']\n",
        "val_loss = history.history['val_loss']\n",
        "\n",
        "plt.figure(figsize=(8, 8))\n",
        "plt.subplot(2, 1, 1)\n",
        "plt.plot(acc, label='Training Accuracy')\n",
        "plt.plot(val_acc, label='Validation Accuracy')\n",
        "plt.legend(loc='lower right')\n",
        "plt.ylabel('Accuracy')\n",
        "plt.ylim([min(plt.ylim()),1])\n",
        "plt.title('Training and Validation Accuracy')\n",
        "\n",
        "plt.subplot(2, 1, 2)\n",
        "plt.plot(loss, label='Training Loss')\n",
        "plt.plot(val_loss, label='Validation Loss')\n",
        "plt.legend(loc='upper right')\n",
        "plt.ylabel('Cross Entropy')\n",
        "plt.ylim([0,1.0])\n",
        "plt.title('Training and Validation Loss')\n",
        "plt.xlabel('epoch')\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "foWMyyUHbc1j"
      },
      "source": [
        "Note: If you are wondering why the validation metrics are clearly better than the training metrics, the main factor is because layers like `tf.keras.layers.BatchNormalization` and `tf.keras.layers.Dropout` affect accuracy during training. They are turned off when calculating validation loss.\n",
        "\n",
        "To a lesser extent, it is also because training metrics report the average for an epoch, while validation metrics are evaluated after the epoch, so validation metrics see a model that has trained slightly longer."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CqwV-CRdS6Nv"
      },
      "source": [
        "## Fine tuning\n",
        "In the feature extraction experiment, you were only training a few layers on top of an MobileNet V2 base model. The weights of the pre-trained network were **not** updated during training.\n",
        "\n",
        "One way to increase performance even further is to train (or \"fine-tune\") the weights of the top layers of the pre-trained model alongside the training of the classifier you added. The training process will force the weights to be tuned from generic feature maps to features associated specifically with the dataset.\n",
        "\n",
        "Note: This should only be attempted after you have trained the top-level classifier with the pre-trained model set to non-trainable. If you add a randomly initialized classifier on top of a pre-trained model and attempt to train all layers jointly, the magnitude of the gradient updates will be too large (due to the random weights from the classifier) and your pre-trained model will forget what it has learned.\n",
        "\n",
        "Also, you should try to fine-tune a small number of top layers rather than the whole MobileNet model. In most convolutional networks, the higher up a layer is, the more specialized it is. The first few layers learn very simple and generic features that generalize to almost all types of images. As you go higher up, the features are increasingly more specific to the dataset on which the model was trained. The goal of fine-tuning is to adapt these specialized features to work with the new dataset, rather than overwrite the generic learning."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CPXnzUK0QonF"
      },
      "source": [
        "### Un-freeze the top layers of the model\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rfxv_ifotQak"
      },
      "source": [
        "All you need to do is unfreeze the `base_model` and set the bottom layers to be un-trainable. Then, you should recompile the model (necessary for these changes to take effect), and resume training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4nzcagVitLQm"
      },
      "outputs": [],
      "source": [
        "base_model.trainable = True"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-4HgVAacRs5v"
      },
      "outputs": [],
      "source": [
        "# Let's take a look to see how many layers are in the base model\n",
        "print(\"Number of layers in the base model: \", len(base_model.layers))\n",
        "\n",
        "# Fine-tune from this layer onwards\n",
        "fine_tune_at = 100\n",
        "\n",
        "# Freeze all the layers before the `fine_tune_at` layer\n",
        "for layer in base_model.layers[:fine_tune_at]:\n",
        "  layer.trainable =  False"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4Uk1dgsxT0IS"
      },
      "source": [
        "### Compile the model\n",
        "\n",
        "As you are training a much larger model and want to readapt the pretrained weights, it is important to use a lower learning rate at this stage. Otherwise, your model could overfit very quickly."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NtUnaz0WUDva"
      },
      "outputs": [],
      "source": [
        "model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n",
        "              optimizer = tf.keras.optimizers.RMSprop(lr=base_learning_rate/10),\n",
        "              metrics=['accuracy'])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WwBWy7J2kZvA"
      },
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bNXelbMQtonr"
      },
      "outputs": [],
      "source": [
        "len(model.trainable_variables)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4G5O4jd6TuAG"
      },
      "source": [
        "### Continue training the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0foWUN-yDLo_"
      },
      "source": [
        "If you trained to convergence earlier, this step will improve your accuracy by a few percentage points."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ECQLkAsFTlun"
      },
      "outputs": [],
      "source": [
        "fine_tune_epochs = 10\n",
        "total_epochs =  initial_epochs + fine_tune_epochs\n",
        "\n",
        "history_fine = model.fit(train_dataset,\n",
        "                         epochs=total_epochs,\n",
        "                         initial_epoch=history.epoch[-1],\n",
        "                         validation_data=validation_dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TfXEmsxQf6eP"
      },
      "source": [
        "Let's take a look at the learning curves of the training and validation accuracy/loss when fine-tuning the last few layers of the MobileNet V2 base model and training the classifier on top of it. The validation loss is much higher than the training loss, so you may get some overfitting.\n",
        "\n",
        "You may also get some overfitting as the new training set is relatively small and similar to the original MobileNet V2 datasets.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DNtfNZKlInGT"
      },
      "source": [
        "After fine tuning the model nearly reaches 98% accuracy on the validation set."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PpA8PlpQKygw"
      },
      "outputs": [],
      "source": [
        "acc += history_fine.history['accuracy']\n",
        "val_acc += history_fine.history['val_accuracy']\n",
        "\n",
        "loss += history_fine.history['loss']\n",
        "val_loss += history_fine.history['val_loss']"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "chW103JUItdk"
      },
      "outputs": [],
      "source": [
        "plt.figure(figsize=(8, 8))\n",
        "plt.subplot(2, 1, 1)\n",
        "plt.plot(acc, label='Training Accuracy')\n",
        "plt.plot(val_acc, label='Validation Accuracy')\n",
        "plt.ylim([0.8, 1])\n",
        "plt.plot([initial_epochs-1,initial_epochs-1],\n",
        "          plt.ylim(), label='Start Fine Tuning')\n",
        "plt.legend(loc='lower right')\n",
        "plt.title('Training and Validation Accuracy')\n",
        "\n",
        "plt.subplot(2, 1, 2)\n",
        "plt.plot(loss, label='Training Loss')\n",
        "plt.plot(val_loss, label='Validation Loss')\n",
        "plt.ylim([0, 1.0])\n",
        "plt.plot([initial_epochs-1,initial_epochs-1],\n",
        "         plt.ylim(), label='Start Fine Tuning')\n",
        "plt.legend(loc='upper right')\n",
        "plt.title('Training and Validation Loss')\n",
        "plt.xlabel('epoch')\n",
        "plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R6cWgjgfrsn5"
      },
      "source": [
        "### Evaluation and prediction"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PSXH7PRMxOi5"
      },
      "source": [
        "Finaly you can verify the performance of the model on new data using test set."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2KyNhagHwfar"
      },
      "outputs": [],
      "source": [
        "loss, accuracy = model.evaluate(test_dataset)\n",
        "print('Test accuracy :', accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8UjS5ukZfOcR"
      },
      "source": [
        "And now you are all set to use this model to predict if your pet is a cat or dog."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RUNoQNgtfNgt"
      },
      "outputs": [],
      "source": [
        "#Retrieve a batch of images from the test set\n",
        "image_batch, label_batch = test_dataset.as_numpy_iterator().next()\n",
        "predictions = model.predict_on_batch(image_batch).flatten()\n",
        "\n",
        "# Apply a sigmoid since our model returns logits\n",
        "predictions = tf.nn.sigmoid(predictions)\n",
        "predictions = tf.where(predictions < 0.5, 0, 1)\n",
        "\n",
        "print('Predictions:\\n', predictions.numpy())\n",
        "print('Labels:\\n', label_batch)\n",
        "\n",
        "plt.figure(figsize=(10, 10))\n",
        "for i in range(9):\n",
        "  ax = plt.subplot(3, 3, i + 1)\n",
        "  plt.imshow(image_batch[i].astype(\"uint8\"))\n",
        "  plt.title(class_names[predictions[i]])\n",
        "  plt.axis(\"off\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_TZTwG7nhm0C"
      },
      "source": [
        "## Summary\n",
        "\n",
        "* **Using a pre-trained model for feature extraction**:  When working with a small dataset, it is a common practice to take advantage of features learned by a model trained on a larger dataset in the same domain. This is done by instantiating the pre-trained model and adding a fully-connected classifier on top. The pre-trained model is \"frozen\" and only the weights of the classifier get updated during training.\n",
        "In this case, the convolutional base extracted all the features associated with each image and you just trained a classifier that determines the image class given that set of extracted features.\n",
        "\n",
        "* **Fine-tuning a pre-trained model**: To further improve performance, one might want to repurpose the top-level layers of the pre-trained models to the new dataset via fine-tuning.\n",
        "In this case, you tuned your weights such that your model learned high-level features specific to the dataset. This technique is usually recommended when the training dataset is large and very similar to the original dataset that the pre-trained model was trained on.\n",
        "\n",
        "To learn more, visit the [Transfer learning guide](https://www.tensorflow.org/guide/keras/transfer_learning).\n"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "transfer_learning.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
